package com.example.mapreduce.mapJon;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * ClassName: MapJoinMapper
 * Package: com.example.mapreduce.mapJon
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-07-17
 * Time: 20:27
 */

public class MapJoinMapper extends Mapper<LongWritable, Text, Text, NullWritable> {
    private HashMap<String, String> pdMap = new HashMap<>();
    private Text outK = new Text();

    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
        //获取缓存文件 并把文件内容封装到集合
        //其实就是缓存一张pd.txt
        //取出缓存地址
        URI[] cacheFiles = context.getCacheFiles();
        FileSystem fs = FileSystem.get(context.getConfiguration());
        FSDataInputStream open = fs.open(new Path(cacheFiles[0]));
        //从流中读取数据
        BufferedReader reader = new BufferedReader(new InputStreamReader(open, "UTF-8"));
        String line;
        while (StringUtils.isNotEmpty(line = reader.readLine())) {
            //切割
            String[] split = line.split("\t");

            pdMap.put(split[0], split[1]);
        }
        //关流
        IOUtils.closeStream(reader);
    }


    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        //处理order
        //获取一行
        String s = value.toString();
        //切割
        String[] split = s.split("\t");

        //获取pid
        String panme = pdMap.get(split[1]);

        //获取订单id 和 订单数量
        //封装
        outK.set(split[0] + "\t" + panme + "\t" + split[2]);
        context.write(outK,NullWritable.get());

    }


}
